if not pattern then pattern = {} end

if not pattern.volume_exit_act then

dofile (ScriptsRootPath .. "lib\\lib.lua")
dofile (ScriptsRootPath .. "lib\\orders.lua")
dofile (ScriptsRootPath .. "lib\\actions.lua")

pattern.volume_exit_act = {do_exit = false}

function pattern.volume_exit_act.OnCandle(source, index, data)
	if not source then return end
	
	if not index then index = 1 end
	
	local after = lib:GetLastCandle(source, index)
	local candle = lib:GetLastCandle(source, index + 1)
	local before = lib:GetLastCandle(source, index + 20)
	
	if not (candle and candle.instrument and before and after) then return end
	
	local is_long
	
	if before.high < candle.low and before.high < after.low then is_long = true end
	if before.low > candle.high and before.low > after.high then is_long = false end
	
	if is_long == nil then return end
	
	if is_long and candle.close - candle.open >= 0 then return end
	if is_long and after.close - after.open >= 0 then return end
	
	if not is_long and candle.close - candle.open <= 0 then return end
	if not is_long and after.close - after.open <= 0 then return end
	
	if candle.volume >= after.volume then return end
	
	local pos = orders:GetPosition(candle.instrument)
	if pos == 0 then return end
	
	if pattern.volume_exit_act.do_exit then
		actions:Exit(candle.instrument)
	end
	
	local price = candle.low
	if is_long then price = candle.high end
	
	candle.datetime.is_long__ = is_long
	candle.datetime.hint__ = lib:FormatPrice(price, candle.instrument)
			
	candle.datetime.notify__ = string.format("%s VOLEXIT %s",
		candle.instrument.code,
		lib:FormatPrice(price, candle.instrument)
	)
	
	return price, candle.datetime
end

end -- of file
